import React, { Component } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Select,
  DatePicker,
  Table,
  Tag,
  Space,
  Image,
  Modal,
  message,
} from 'antd'
import { Link } from 'react-router-dom'
import styles from './index.module.scss'
import { ArticleStatus } from 'api/constants'
import { getChannels } from 'api/channel'
import { getArticles, delArticle } from 'api/article'
import defaultImg from 'assets/error.png'
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
const { confirm } = Modal
const { RangePicker } = DatePicker
const { Option } = Select
export default class ArticleList extends Component {
  state = {
    //频道数据
    channels: [],
    articles: [],
  }
  // 用于存放查询文章列表的所有的参数
  reqParams = {
    page: 1,
    per_page: 10,
  }
  columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render(data) {
        const { images, type } = data
        if (type === 0) {
          return (
            <Image width={200} preview={false} height={150} src={defaultImg} />
          )
        }
        return (
          <Image
            width={200}
            height={150}
            src={images[0]}
            fallback={defaultImg}
          />
        )
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(status) {
        const obj = ArticleStatus.find((item) => item.id === status)
        console.log(status)
        return <Tag color={obj.color}>{obj.name}</Tag>
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render: (data) => {
        return (
          <Space>
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined onClick={() => this.handleEdit(data.id)} />}
            ></Button>
            <Button
              type="primary"
              shape="circle"
              danger
              icon={<DeleteOutlined />}
              onClick={() => this.handleDelete(data.id)}
            ></Button>
          </Space>
        )
      },
    },
  ]
  render() {
    const { total_count, results, page, per_page } = this.state.articles
    return (
      <div className={styles.articleList}>
        <Card
          title={
            <Breadcrumb separator="/">
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>文章列表</Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form initialValues={{ status: -1 }} onFinish={this.onFinish}>
            <Form.Item label="状态" name="status">
              <Radio.Group>
                {ArticleStatus.map((item) => (
                  <Radio key={item.id} value={item.id}>
                    {item.name}
                  </Radio>
                ))}
                {/* <Radio value={-1}>全部</Radio>
                <Radio value={0}>草稿</Radio>
                <Radio value={1}>待审核</Radio>
                <Radio value={2}>审核通过</Radio>
                <Radio value={3}>审核失败</Radio> */}
              </Radio.Group>
            </Form.Item>

            <Form.Item label="频道" name="channel_id">
              <Select placeholder="请选择频道" style={{ width: 200 }}>
                {this.state.channels.map((item) => (
                  <Option key={item.id} value={item.id}>
                    {item.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item label="日期" name="">
              <RangePicker />
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit">
                筛选
              </Button>
            </Form.Item>
          </Form>
        </Card>
        <Card title={`根据筛选条件共查询到${total_count}条数据`}>
          <Table
            dataSource={results}
            columns={this.columns}
            rowKey="id"
            pagination={{
              position: ['bottomCenter'],
              current: page,
              pageSize: per_page,
              total: total_count,
              // 每页大小 或者 页码 改变时，触发的事件
              onChange: this.changePage,
            }}
          />
        </Card>
      </div>
    )
  }
  //修改文章
  handleEdit = (id) => {
    this.props.history.push(`/home/publish/${id}`)
  }
  //删除文章
  handleDelete = (id) => {
    console.log(id, 'id')
    confirm({
      title: '温馨提示？',
      icon: <ExclamationCircleOutlined />,
      content: '你确定要删除文章吗',
      onOk: async () => {
        // 发送请求进行删除
        await delArticle(id)
        //重新获取文章列表
        this.getArticleList()
        //提示消息
        message.success('删除成功')
      },
    })
  }
  async getChannelList() {
    const res = await getChannels()
    this.setState({
      channels: res.data.channels,
    })
  }
  async getArticleList() {
    const res = await getArticles()
    console.log(res, '数据')
    this.setState({
      articles: res.data,
    })
  }
  componentDidMount() {
    this.getChannelList()
    this.getArticleList()
  }
  changePage = async (page, pageSize) => {
    console.log(page, pageSize)
    const res = await getArticles({
      page,
      per_page: pageSize,
    })
    this.setState({
      articles: res.data,
    })
  }
  onFinish = async ({ status, channel_id, date }) => {
    // 处理状态
    if (status !== -1) {
      this.reqParams.status = status
    } else {
      delete this.reqParams.status
    }
    // 处理频道
    if (channel_id) {
      this.reqParams.channel_id = channel_id
    } else {
      delete this.reqParams.channel_id
    }
    // 处理日期
    if (date) {
      this.reqParams.begin_pubdate = date[0].startOf('day').format('YYYY-MM-DD')
      this.reqParams.end_pubdate = date[1].endOf('day').format('YYYY-MM-DD')
    } else {
      delete this.reqParams.begin_pubdate
      delete this.reqParams.end_pubdate
    }
    //如果是查询的操作 页码为1
    this.reqParams.page = 1
    const res = await getArticles(this.reqParams)
    console.log(res.data)
    this.setState({
      articles: res.data,
    })
  }
}
